package com.dynamic.lesscss.engine;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;

import com.asual.lesscss.LessEngine;
import com.asual.lesscss.LessException;
import com.asual.lesscss.LessOptions;

public abstract class AbstractAction {
	/***
	 * 
	 * @throws LessException
	 * @throws IOException
	 */
	public void compileFile(IResource file){
		if(file==null){
			return;
		}
		try {
			String inputPath =file.getLocation().makeAbsolute().toFile().getAbsolutePath();
			String outputPath = inputPath.substring(0, inputPath.lastIndexOf(".")) + ".css";
			LessOptions options = new LessOptions();
			options.setCss(true);
			LessEngine engine = new LessEngine(options);
			String output = engine.compile(new File(inputPath));
			//String output = engine.compile(this.getInput(inputPath));
			if(output.trim().equals("")){
				return;
			}
			this.writeOut(outputPath,output);
			System.out.print("Compile Lesscss Out :"+outputPath);
		} catch (LessException e) {
			e.printStackTrace();
		} 
	}
	protected void compileFolder(IResource resource) {
		// 如果是文件夹
		if ((resource instanceof IFolder)) {
			IFolder folder = (IFolder) resource;
			try {
				IResource[] resources = folder.members();
				for (IResource r : resources) {
					compileFolder(r);
				}
			} catch (CoreException e) {
				
			}
		} else if (resource instanceof IFile) {
			compileFile(resource);
		}
	}
	/***
	 * 利用FileInputStream读取文件
	 * @param path
	 * @return
	 * @throws IOException
	 */
	public String getInput(String path) throws IOException{
		File file = new File(path);
		if (!file.exists() || file.isDirectory()) {
			throw new FileNotFoundException();
		}
		BufferedReader br = new BufferedReader(new FileReader(file));
		String temp = null;
		StringBuffer sb = new StringBuffer();
		temp = br.readLine();
		while (temp != null) {
			sb.append(temp);
			sb.append("\r\n");
			temp = br.readLine();
		}
		br.close();
		return sb.toString();
    }
	/***
	 * 
	 * @param output
	 */
	private void writeOut(String outputPath,String content){
		try {
			FileOutputStream out = new FileOutputStream(outputPath);
			PrintStream print = new PrintStream(out);
			print.println(content);
			print.close();
			out.close(); 
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
